package com.example.shixun.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.example.shixun.interceptor.Login;
import com.example.shixun.pojo.*;
import com.example.shixun.service.CourseStudentService;
import com.example.shixun.service.SchoolUserService;
import com.example.shixun.service.UserService;
import com.example.shixun.service.impl.UserServiceImpl;
import com.example.shixun.utils.GetQQImgUrl;
import com.example.shixun.utils.PageInfoUtil;
import com.example.shixun.utils.RedisUtils;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Param;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Controller
@ResponseBody
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RedisUtils redisUtils;
    @Resource
    private SchoolUserService schoolUserService;
    @Resource
    private CourseStudentService courseStudentService;
//    @RequestMapping("/login")
//    public Integer login(@RequestBody User user){
//        return userService.login(user);
//    }

//    /**
//     *
//     * @param email
//     * @param password
//     * */
    //@RequestMapping(value = "/login",method = RequestMethod.GET)
    @PostMapping("/login")
    public Result<Integer> index(@RequestBody User user, HttpServletRequest request){
    //public Result<Integer> index(String email,String password, HttpServletRequest request){
        System.out.println("访问登录界面");
        //System.out.println(email+":"+password);
        if(user.getEmail()==null||user.getPassword()==null){
            return Result.fail("邮箱或密码为空！");
        }
        if(!userService.findEmail(user.getEmail()).getSuccess()){
            return Result.fail("该邮箱未注册");
        }
        user.setEmail(user.getEmail());
        user.setPassword(user.getPassword());
        Result r = userService.login(user);
        if(r.getSuccess()){
            HttpSession session= request.getSession();
            session.setAttribute("user",user);
        }
        return r;
    }
    @ApiOperation("注册")
    @PostMapping("register")
    public Result register(@RequestBody Map<String, String> param) {
        System.out.println(param.toString());
        String email=param.get("email");
        String code=param.get("code");
        if(userService.findEmail(email).getSuccess()){

            return Result.fail("该邮箱已被注册");
        }
        if(!code.equals(redisUtils.get(param.get("email")))){
            System.out.println(code+"!="+RedisUtils.get(param.get("email")));
            return Result.fail("验证码不正确");
        }
        User user=new User();
        if(user.getAvatar()==null||user.getAvatar()==""){
            String avatar=GetQQImgUrl.getQQNumberFromEmail(email);
            System.out.println(avatar);
            user.setAvatar(avatar);
        }
        user.setName(param.get("name"));
        user.setEmail(email);
        user.setPassword(param.get("password"));
        userService.register(user);
        System.out.println("code:"+code);
        return Result.success("注册成功");
    }
    @ApiOperation("重置密码")
    @PostMapping("resetPwd")
    public Result resetPwd(@RequestBody Map<String,String> param){
        String code = param.get("code");
        String email = param.get("email");
        System.out.println("email:"+email+" code:"+code);
        if(code==null||email==null){
            return Result.fail("请填写完整信息");
        }
        if(!code.equals(redisUtils.get(email))){
            System.out.println(code+"!="+stringRedisTemplate.opsForValue().get(email));
            return Result.fail("验证码错误");
        }
        if(!userService.findEmail(email).getSuccess()){
            return Result.fail("该邮箱未注册");
        }
        User user = new User();
        user.setEmail(email);
        user.setPassword(param.get("password"));
        return userService.updatePwd(user);
    }
    @ApiOperation("查找邮箱")
    @PostMapping("findEmail")
    public Result findEmail(@RequestParam("email") String email){
        return userService.findEmail(email);
    }

    /**
     *
     *
     * @param pageNum 当前页码
     * @param pageSize 页面大小
     * @param user 学生信息，如name=lys
     * @return
     */
    @ApiOperation("分页查找学生")
    @GetMapping("/list")
    public Result getStudentList(@RequestParam(value = "pageNum", defaultValue = "1")Integer pageNum,
                                 @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
                                 @RequestParam(value = "orderBy", defaultValue = "name") String orderBy,
                                 @RequestParam(value = "order", defaultValue = "asc") String order,
                                 User user){
        System.out.println("用户姓名:"+user.toString());
        PageInfoUtil<User> pageInfoUtil =new PageInfoUtil<User>();
        String[] orderByArr = {"like_number","score","create_time"};
        String orderByStr = "";
        System.out.println("orderBy:"+orderBy+" order:"+order);
        if (orderBy!=null&&orderBy!="" && Arrays.asList(orderByArr).contains(orderBy.toLowerCase())) {
            orderByStr = String.format("%s %s", orderBy.toLowerCase(), "asc".equalsIgnoreCase(order) ? "asc" : "desc");
        } else {
            // 默认排序
            orderByStr = "name asc";
        }
        pageInfoUtil.setPageNum(pageNum);
        pageInfoUtil.setPageSize(pageSize);
        System.out.println(pageSize);
        pageInfoUtil.setParams(user);
        pageInfoUtil.setOrderBy(orderByStr);
        PageInfoUtil<User> pageInfo= this.userService.getStudentList(pageInfoUtil);
        return  Result.success(pageInfo);
    }
    @ApiOperation("根据token获取用户部分信息")
    @Login
    @GetMapping("info")
    public Result info(@RequestHeader("token") String token) {
//        System.out.println("token="+token);
        if (token == null) return Result.fail("token==null");
        UserDTO user = userService.getUserTokenInfo(token);
        System.out.println("userDTO="+user);
        String jsonStr = JSON.toJSONString(user, SerializerFeature.WriteDateUseDateFormat);
        Map<String, Object> map = JSON.parseObject(jsonStr, new TypeReference<Map<String, Object>>() {});
        System.out.println("map="+map);
        return Result.success(map);
    }
    @ApiOperation("根据token获取用户id")
    @Login
    @GetMapping("getId")
    public Integer getId(@RequestHeader("token") String token) {
//        System.out.println("token="+token);
        if (token == null) return -1;
        if(userService==null){
            userService=new UserServiceImpl();
        }
        UserDTO user;
        user=userService.getUserTokenInfo(token);
        System.out.println("userDTO="+userService.getUserTokenInfo(token));
        return user.getId();
    }
    @ApiOperation("根据token里的id获取用户信息")
    @Login
    @GetMapping("infoById")
    public Result infoById(@RequestHeader("token") String token) {
//        System.out.println("token="+token);
        if (token == null) return Result.fail("token==null");
        UserDTO user = userService.getUserTokenInfo(token);
        System.out.println("userDTO="+user);
        String jsonStr = JSON.toJSONString(user, SerializerFeature.WriteDateUseDateFormat);
        Map<String, Object> map = JSON.parseObject(jsonStr, new TypeReference<Map<String, Object>>() {});
//        System.out.println("map="+map);
        return Result.success(userService.getUserById((Integer) map.get("id")));
    }
    @ApiOperation("传入老师id获取用户信息")
    @GetMapping("findByTeacherId")
    public Result findByTeacherId(@RequestParam("teacherId") Integer id) {
        System.out.println("teacherId="+id);
        return Result.success(userService.getUserById(id));
    }
    @ApiOperation("传入id获取用户信息")
    @GetMapping("findById")
    public Result findById(@RequestParam("id") Integer id) {
        System.out.println("id="+id);
        return Result.success(userService.getUserById(id));
    }
    @ApiOperation("修改学生信息")
    @Login
    @PostMapping("/updateInfo")
    public Result updateInfo(@RequestBody User user,
                             @RequestHeader("token") String token){
        Integer id=this.getId(token);
        System.out.println("id="+id);
        user.setId(id);
        return userService.updateUser(user);
    }
    @ApiOperation("修改学生为老师")
    @GetMapping("/setTeacher")
    public Result setTeacher(@RequestParam("id") Integer id){
        return userService.setTeacher(id);
    }
    @ApiOperation("修改老师为学生")
    @GetMapping("/setStudent")
    public Result setStudent(@RequestParam("id") Integer id){
        return userService.setStudent(id);
    }
    @ApiOperation("删除用户")
    @GetMapping("/delete")
    public Result deleteUser(Integer id){
        Integer n = userService.setStatus_1(id);
        if(n==null||n<1) return Result.fail("删除失败，请检查id");
        return Result.success(n);
    }
    @ApiOperation("恢复删除的用户")
    @GetMapping("/reuser")
    public Result reUser(Integer id){
        Integer n = userService.setStatus_0(id);
        if(n==null||n<1) return Result.fail("恢复失败，请检查id");
        return Result.success(n);
    }
    @ApiOperation("根据学校id获取老师信息")
    @GetMapping("/findBySchoolId")
    public Result findBySchoolId(Integer id){
        List<SchoolUser> userIdList = schoolUserService.findBySchoolId(id);
        List<User> userList=new ArrayList<>();
        for(SchoolUser list:userIdList){
            Integer uid= list.getUserId();
            userList.add((User) userService.getUserById(uid).getData());
        }
        return Result.success(userList);
    }
    @ApiOperation("根据课程id查找所有学生")
    @GetMapping("/findByCourseId")
    public Result findByCourseId(@RequestParam("courseId") Integer courseId){
        List<CourseStudent> studentIdLists = courseStudentService.selectCourseStudentByCourseId(courseId);
        List<StudiedUserDTO> studiedUserDTOList=new ArrayList<>();
        for(CourseStudent sid:studentIdLists){
            StudiedUserDTO studiedUserDTO=new StudiedUserDTO();
            studiedUserDTO.setCreateTime(sid.getCreateTime());
            User user=(User) userService.getUserById(sid.getStudentId()).getData();
            studiedUserDTO.setId(user.getId());
            studiedUserDTO.setName(user.getName());
            studiedUserDTO.setEmail(user.getEmail());
            studiedUserDTOList.add(studiedUserDTO);
        }
        return Result.success(studiedUserDTOList);
    }
}
